package com.uenpay.im.ui.old.activity.chat;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.protocol.BaseContentModel;
import com.qyx.android.protocol.QyxMsg;
import com.qyx.android.protocol.QyxTopMsg;
import com.qyx.android.protocol.SessionModel;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.group.AddGroupMemberActivity;
import com.uenpay.im.ui.old.activity.red.RedHandler;
import com.uenpay.im.adapter.SelectedTalkListAdapter;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.entities.chatbean.MsgRedModel;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.util.app.base.BaseActivity;

import java.text.MessageFormat;
import java.util.ArrayList;

/**
 * @author SL
 * @date 2014/7/23
 * @copyRight http://www.qiyunxin.com
 */
public class PickTalkActivity extends BaseActivity {
    private ListView listView;
    private SelectedTalkListAdapter adapter;
    private TextView title;
    private TopListMsgManager topListMsgManager = new TopListMsgManager();
    private BaseContentModel forwardMsg;
    private View loading;

    public void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.pick_talk_view;
    }

    @Override
    public void initView(View view) {
        initView();
        Bundle bu = getIntent().getExtras();
        forwardMsg = bu.getParcelable("forwardMsg");
        adapter = new SelectedTalkListAdapter(this);
        listView.setAdapter(adapter);
        initListener();
        new QueryDataFromDBTask().execute();
    }

    class QueryDataFromDBTask extends AsyncTask<Void, Void, Void> {
        ArrayList<QyxTopMsg> _list = new ArrayList<QyxTopMsg>();

        @Override
        protected Void doInBackground(Void... params) {
            try {
                _list = topListMsgManager.queryChat();

            } catch (Exception e) {
                Log.e("e", e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            adapter.setData(_list);
            super.onPostExecute(aVoid);
        }
    }

    protected void initView() {
        loading = findViewById(R.id.loading);
        title = (TextView) findViewById(R.id.title_textview);
        ((TextView) findViewById(R.id.title_right_tv)).setText(getResources()
                .getString(R.string.sure));
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        listView = (ListView) findViewById(R.id.pick_talk_list);
        View headerView = View.inflate(PickTalkActivity.this,
                R.layout.pick_talk_header, null);
        listView.addHeaderView(headerView);
        title.setText(R.string.select);
        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bu = new Bundle();
                bu.putParcelable("forwardMsg", forwardMsg);
                Utils.startActivityForResult(PickTalkActivity.this,
                        AddGroupMemberActivity.class, bu, 100);
            }
        });
    }

    protected void initListener() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (position == 0) {
                    return;
                }
                adapter.setSelectedItem(position - 1);
            }
        });
        findViewById(R.id.title_right_layout).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (adapter.getSelectedItem() == null) {
                            return;
                        }
                        QyxTopMsg msg = adapter.getSelectedItem();
                        if (forwardMsg != null) {
                            forwardDialog(msg.chat_name, msg.sessionModel);
                        }

                    }
                });

    }

    private void forwardDialog(final String chatName,
                               final SessionModel sessionModel) {
        DialogUtility.showDialog(PickTalkActivity.this, MessageFormat.format(
                getResources().getString(R.string.forward_dialog), chatName),
                R.string.yes, R.string.no, true, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {

                        if (forwardMsg.getType() == MsgContentType.RED) {
                            sendRed(chatName, sessionModel);
                        } else {
                            startChat(chatName, sessionModel);
                        }
                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {
            SessionModel sessionModel = (SessionModel) data
                    .getParcelableExtra("session");
            String stranger_name = data.getStringExtra("stranger_name");
            if (sessionModel != null) {
                forwardDialog(stranger_name, sessionModel);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private RedHandler mRedHandler = new RedHandler();

    private void sendRed(final String chatName, final SessionModel sessionModel) {
        loading.setVisibility(View.VISIBLE);
        String red_packet_id = "";
        MsgRedModel msgRedModel = (MsgRedModel) forwardMsg;
        if (msgRedModel != null) {
            red_packet_id = msgRedModel.getPacketsid();
        }

        mRedHandler.sendRed(red_packet_id, sessionModel.getSessionId() + "",
                sessionModel.getSessionType(), new RedHandler.ISendRedResult() {

                    @Override
                    public void onSendResult(int status, String reason) {
                        loading.setVisibility(View.GONE);
                        if (status == HttpInvokeResultCode.RESULT_OK)
                            startChat(chatName, sessionModel);
                    }
                });
    }

    // private void startChat(QyxTopMsg qyxTopMsg) {
    // forwardMsg.setToCustName(qyxTopMsg.chat_name);
    // SendMsgHandle.sendMsg(forwardMsg, qyxTopMsg.sessionModel,
    // new ISendMsgCallBack() {
    //
    // @Override
    // public void onSendMsgResult(boolean isFriend, QyxMsg qyxMsg) {
    // //IMApplication.showToast(R.string.success);
    // }
    // }, new IUploadAttachFaild() {
    //
    // @Override
    // public void onUploadFailed(String msg_no) {
    //
    // }
    // });
    //
    // // Intent intent = new Intent(PickTalkActivity.this,
    // // ChatActivity.class);
    // // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    // // Bundle bu = new Bundle();
    // // bu.putParcelable("session", qyxTopMsg.sessionModel);
    // // bu.putString("stranger_name", qyxTopMsg.chat_name);
    // // bu.putInt("unread_msg_count", qyxTopMsg.msg_count);
    // // bu.putParcelable("forwardMsg", forwardMsg);
    // // intent.putExtras(bu);
    // // startActivity(intent);
    // setResult(RESULT_OK);
    // finish();
    // }

    private void startChat(String chat_name, SessionModel sessionModel) {
        forwardMsg.setToCustName(chat_name);
        SendMsgHandle.sendMsg(forwardMsg, sessionModel, new SendMsgHandle.ISendMsgCallBack() {

            @Override
            public void onSendMsgResult(int sendMsgResult, QyxMsg qyxMsg) {
                // IMApplication.showToast(R.string.success);
            }
        }, new SendMsgHandle.IUploadAttachFaild() {

            @Override
            public void onUploadFailed(String msg_no) {

            }
        });
        setResult(RESULT_OK);
        finish();
    }
}